<template>
  <div class="page-container">
    <template v-if="!showDetail">
      <div class="top-container">
        <div class="left-section">
          <el-checkbox
            v-model="isAllSelected"
            @change="handleSelectAll"
            class="select-all-checkbox"
          >
            全选
          </el-checkbox>
        </div>
        <div class="right-section">
          <el-select v-model="videoType" placeholder="图片类型" class="video-type custom-select" @change="handleTypeChange">
            <el-option label="图生图" value="image_to_images" />
            <el-option label="文生图" value="text_to_images" />
            <el-option label="拼图" value="type3" />
            <el-option label="手稿变图" value="graffiti_painting" />
            <el-option label="人像重绘" value="portrait_style_repainting" />
            <el-option label="图像修复" value="super_resolution_image" />
            <el-option label="海报生成" value="type7" />
          </el-select>
          <el-input
              v-model="searchText"
              placeholder="请输入搜索内容"
              class="search-input custom-input"
              :prefix-icon="Search"
              @keyup.enter="handleSearch"
          />
          <el-divider direction="vertical" />
          <el-button type="primary" @click="sendSelectMaterialConfirm">
            <el-icon style="margin-right: 5px;">
              <Check />
            </el-icon>
            确定
          </el-button>
        </div>
      </div>
      <div class="content-wrapper">
        <div class="content-list">
          <el-row :gutter="24">
            <el-col :span="12" v-for="item in pageData" :key="item.id">
              <div class="card" @click="handleCardClick(item.id)">
                <div class="card-header">
                  <el-checkbox v-model="item.checked" @click.stop @change="handleCheckboxChange(item, $event)"/>
                  <span class="card-title">{{ item.title }}</span>
                  <span class="card-meta-info">{{ item.classify_name }} {{ item.addtime }}</span>
                </div>
                <div class="card-body">
                  <img :src="item.image_url" class="card-img" />
                  <div class="card-info">
                    <div class="card-count">
                      <span class="count">{{ item.success_count }}</span> 个
                      <div class="desc">成品总量</div>
                    </div>
                    <div class="card-meta">
                      <div>
                        <span class="count">{{ item.fb_num }}</span> 个
                        <div class="desc">已发布数量</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="pagination-bar">
          <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              :page-size="pageSize"
              :current-page="currentPage"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              :page-sizes="[10,20,50,100]"
          />
        </div>
      </div>
      <el-dialog v-model="showDeleteDialog" title="确认删除" width="300px" :close-on-click-modal="false">
        <span>确定要删除吗？</span>
        <template #footer>
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="handleConfirmDelete">确定</el-button>
        </template>
      </el-dialog>
      <MyDialog v-model="showMobileDownloadDialog" width="420px" @confirm="handleConfirm" title="请使用手机扫码下载">
        <div style="text-align:center; padding: 16px 0;">
          <img src="/pictureDownLoadPhone.png" alt="二维码" style="width:180px; height:180px;" />
        </div>
      </MyDialog>
    </template>
    <ProductPictureDetail v-else :video-id="selectedVideoId" :select-pic-son-item="selectPicSonItem" @back="handleBack" @update:select-pic-son-item="handleUpdateSelection" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import axiosUtil from '../../axios-util/axios-util'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import ProductPictureDetail from './ProductPictureDetailNew.vue'
import {useRouter} from "vue-router";
import MyDialog from '../common/MyDialog.vue'
import utils from '../../utils/utils';

//主题控制light  dark
//主题控制light  dark
const theme = utils.getTheme();
const website_bg_url = ref('')
const router = useRouter()

const videoType = ref('image_to_images')
const searchText = ref('')

const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const pageData = ref([])
const loading = ref(false)

const showDetail = ref(false)
const selectedVideoId = ref<number | null>(null)

const showDeleteDialog = ref(false)
const showMobileDownloadDialog = ref(false)
const isAllSelected = ref(false)

const emit = defineEmits(['confirm']);

const fetchList = async () => {
  loading.value = true
  let url = ''
  let params = {}
  if(videoType.value === 'type3'){
    url = 'api/imagesplit/list'
    params = {
      id: "",
      offset: currentPage.value,
      type: 1,
      status: "",
      limit: pageSize.value,
      title: searchText.value
    }
  }else if(videoType.value === 'type7'){
    url = 'api/poster/list'
    params = {
      id: "",
      offset: currentPage.value,
      type: 1,
      status: "",
      limit: pageSize.value,
      title: searchText.value
    }
  }else{
    url = 'api/aliyun_tongyi/wan_xiang/image_task_list'
    params = {
      size: pageSize.value,
      page: currentPage.value,
      title: searchText.value,
      type: videoType.value || 'image_to_images',
    }
  }
  const response = await axiosUtil.post(url,params)
  loading.value = false
  if (response.data.code === 1 ) {
    if(videoType.value === 'type3'){
      pageData.value = response.data.data.rows
      total.value = response.data.data.total || 0
      pageData.value.forEach(item => {
        item.image_url = item.video_url_image
        item.checked = false // 初始化选中状态
      })
    }else if(videoType.value === 'type7'){
      pageData.value = response.data.data.rows
      pageData.value.forEach(item => {
        item.image_url = item.video_url_image
        item.checked = false // 初始化选中状态
      })
      total.value = response.data.data.total || 0
    }else{
      pageData.value = response.data.data.list
      total.value = response.data.data.total || 0
      pageData.value.forEach(item => {
        item.checked = false // 初始化选中状态
      })
    }
  }
}

onMounted(() => {
  document.body.classList.remove('login-page')
  initWebsiteBgUrl()
  fetchList()
})

//读取配置，获取网站背景图
const initWebsiteBgUrl = async () => {
  const response = await axiosUtil.post('api/pc/site/get_agent_config', {})
  if (response.data.code === 0 && response.data.data) {
    website_bg_url.value = import.meta.env.VITE_APP_SERVER + response.data.data.website_bg || ''
  }
}

const handleNewTask = () => {
  router.push('/batchVideoBg')
}

const handlePublish = () => {
  // 处理发布
}

const handleDelete = () => {
  showDeleteDialog.value = true
}

const handleConfirmDelete = async () => {
  showDeleteDialog.value = false
  const selectedItems = pageData.value.filter((item: any) => item.checked);
  const selectedIds = selectedItems.map((item: any) => item.id);
  // 这里的接口和参数请根据实际后端接口调整
  const response = await axiosUtil.post('api/aliyun_tongyi/wan_xiang/image_task_delete', {
    ids: selectedIds
  })
  if (response.data.code === 1) {
    ElMessage.success('删除成功')
  } else {
    ElMessage.error('删除失败：' + response.data.msg)
  }
  fetchList()
}

const handleDownloadToPC = () => {
  // 这里写下载到电脑的逻辑
  console.log('下载到电脑')
}

const handleDownloadToMobile = () => {
  showMobileDownloadDialog.value = true
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchList()
}
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchList()
}

// 搜索和筛选
const handleSearch = () => {
  currentPage.value = 1
  fetchList()
}
const handleTypeChange = () => {
  currentPage.value = 1
  fetchList()
}

const handleCardClick = async (id: number) => {
  // 清空所有选择
  selectPicSonItem.value = []
  
  // 清空所有checkbox的选中状态
  pageData.value.forEach((item: any) => {
    item.checked = false
  })
  
  // 更新全选状态
  isAllSelected.value = false
  
  selectedVideoId.value = id
  showDetail.value = true
}

const handleBack = () => {
  showDetail.value = false
  selectedVideoId.value = null
}

const handleUpdateSelection = (newSelection: any[]) => {
  selectPicSonItem.value = newSelection
}

const handleConfirm = () => {
  showMobileDownloadDialog.value = false
}

const selectPicSonItem = ref([])

const getSelectMateriaAll = () => {
  console.log('getSelectMateriaAll called, current selection:', selectPicSonItem.value) // 添加调试日志
  return selectPicSonItem.value
}

// 处理 checkbox 变化
const handleCheckboxChange = async (item: any, checked: boolean) => {
  console.log('checkbox changed:', item.id, checked) // 添加调试日志
  const res = await axiosUtil.post('api/aliyun_tongyi/wan_xiang/query_image_task', {
    id: item.id,
  })
  const picArr = res.data.data.list;
  
  // 遍历 picArr 中的数据，检查是否在 selectPicSonItem 中存在
  picArr.forEach((picItem: any) => {
    const existingIndex = selectPicSonItem.value.findIndex((selectedItem: any) => selectedItem.id === picItem.id)
    
    if (checked) {
      // 选中时，如果不存在则添加到数组
      if (existingIndex === -1) {
        selectPicSonItem.value.push(picItem)
        console.log('added to selection:', picItem.id) // 添加调试日志
      }
    } else {
      // 取消选中时，如果存在则从数组中删除
      if (existingIndex !== -1) {
        selectPicSonItem.value.splice(existingIndex, 1)
        console.log('removed from selection:', picItem.id) // 添加调试日志
      }
    }
  })

  console.log('current selection:', selectPicSonItem.value) // 添加调试日志

  // 更新全选状态
  const checkedCount = pageData.value.filter((item: any) => item.checked).length
  isAllSelected.value = checkedCount === pageData.value.length && pageData.value.length > 0
}

// 全选/取消全选
const handleSelectAll = async (checked: boolean) => {
  console.log('select all changed:', checked) // 添加调试日志

  pageData.value.forEach((item: any) => {
    item.checked = checked
  })

  if (checked) {
    // 全选时，需要遍历每个项目获取其对应的 picArr 数据
    selectPicSonItem.value = [] // 先清空数组
    
    // 遍历每个项目，获取其对应的图片数据
    for (const item of pageData.value) {
      try {
        const res = await axiosUtil.post('api/aliyun_tongyi/wan_xiang/query_image_task', {
          id: item.id,
        })
        const picArr = res.data.data.list
        
        // 将 picArr 中的数据添加到 selectPicSonItem
        picArr.forEach((picItem: any) => {
          const existingIndex = selectPicSonItem.value.findIndex((selectedItem: any) => selectedItem.id === picItem.id)
          if (existingIndex === -1) {
            selectPicSonItem.value.push(picItem)
          }
        })
      } catch (error) {
        console.error('Failed to fetch image task data for item:', item.id, error)
      }
    }
    
    console.log('all items selected:', selectPicSonItem.value.length) // 添加调试日志
  } else {
    // 取消全选时，清空数组
    selectPicSonItem.value = []
    console.log('all items deselected') // 添加调试日志
  }
}

const sendSelectMaterialConfirm = () => {
  emit('confirm');
}

defineExpose({
  getSelectMateriaAll
})
</script>

<style scoped>
.page-container {
  position: relative;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
}

.top-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"');
  backdrop-filter: blur(10px);
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.1)"');
  border-radius: 8px;
  box-shadow: 0 4px 6px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.1)" : "rgba(0, 0, 0, 0.3)"');
  position: relative;
  overflow: hidden;
  margin: 10px 20px;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.select-all-checkbox {
  color: v-bind('theme === "light" ? "#000" : "#fff"');
}

.select-all-checkbox :deep(.el-checkbox__label) {
  color: v-bind('theme === "light" ? "#000" : "#fff"');
}

.select-all-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
  border-color: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
}

.video-type {
  width: 120px;
}

.search-input {
  width: 200px;
}

/* 自定义按钮样式 */
.custom-button {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"') !important;
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
  color: #fff !important;
  transition: all 0.3s ease !important;
}

.custom-button:hover {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.15)" : "rgba(0, 0, 0, 0.4)"') !important;
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.5)"') !important;
}

/* 自定义下拉框样式 */
.custom-select :deep(.el-input__wrapper) {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"') !important;
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
  box-shadow: none !important;
}

.custom-select :deep(.el-input__inner) {
  color: #fff !important;
}

.custom-select :deep(.el-input__wrapper:hover) {
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.5)"') !important;
  box-shadow: 0 0 15px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
}

/* 自定义输入框样式 */
.custom-input :deep(.el-input__wrapper) {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"') !important;
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
  box-shadow: none !important;
}

.custom-input :deep(.el-input__inner) {
  color: #fff !important;
}

.custom-input :deep(.el-input__wrapper:hover) {
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.5)"') !important;
  box-shadow: 0 0 15px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.4)"') !important;
}

/* 下拉选项样式 */
:deep(.el-select-dropdown) {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.95)" : "rgba(0, 0, 0, 0.95)"') !important;
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(255, 255, 255, 0.1)"') !important;
  backdrop-filter: blur(10px);
}

:deep(.el-select-dropdown__item) {
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.8)" : "rgba(255, 255, 255, 0.8)"') !important;
}

:deep(.el-select-dropdown__item.hover),
:deep(.el-select-dropdown__item:hover) {
  background: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.1)" : "rgba(255, 255, 255, 0.1)"') !important;
  color: v-bind('theme === "light" ? "#000" : "#fff"') !important;
}

:deep(.el-select-dropdown__item.selected) {
  background: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.2)" : "rgba(255, 255, 255, 0.2)"') !important;
  color: v-bind('theme === "light" ? "#000" : "#fff"') !important;
}

.content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin: 0 20px 10px;
  min-height: 0;
  overflow: hidden;
}

.content-list {
  flex: 1;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"');
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.1)"');
  border-radius: 12px;
  box-shadow: 0 0 20px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.08)" : "rgba(0, 0, 0, 0.2)"');
  padding: 24px;
  overflow-y: auto;
  margin-bottom: 10px;
}

/* 自定义滚动条样式 */
.content-list::-webkit-scrollbar {
  width: 6px;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.3)"');
}

.content-list::-webkit-scrollbar-thumb {
  background: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.3)" : "linear-gradient(180deg, rgba(0, 255, 255, 0.2), rgba(0, 255, 255, 0.4), rgba(0, 255, 255, 0.2))"');
  border-radius: 3px;
  border: 1px solid v-bind('theme === "light" ? "rgba(0, 0, 0, 0.3)" : "rgba(0, 255, 255, 0.3)"');
  box-shadow: 0 0 10px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.2)" : "rgba(0, 255, 255, 0.2)"');
}

.content-list::-webkit-scrollbar-thumb:hover {
  background: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.4)" : "linear-gradient(180deg, rgba(0, 255, 255, 0.3), rgba(0, 255, 255, 0.5), rgba(0, 255, 255, 0.3))"');
  box-shadow: 0 0 15px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.3)" : "rgba(0, 255, 255, 0.3)"');
}

.content-list::-webkit-scrollbar-track {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.2)"');
  border-radius: 3px;
  border: 1px solid v-bind('theme === "light" ? "rgba(0, 0, 0, 0.1)" : "rgba(0, 255, 255, 0.1)"');
}

.card {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"');
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.1)"');
  border-radius: 10px;
  margin-bottom: 24px;
  padding: 18px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 0 10px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.08)" : "rgba(0, 0, 0, 0.2)"');
  transition: all 0.3s ease;
  cursor: pointer;
}

.card:hover {
  box-shadow: 0 0 24px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.18)" : "rgba(0, 0, 0, 0.3)"');
  transform: translateY(-2px);
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.4)" : "rgba(255, 255, 255, 0.2)"');
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 8px;
}

.card-title {
  font-weight: bold;
  color: v-bind('theme === "light" ? "#000" : "#fff"');
  font-size: 1.1em;
}

.card-meta-info {
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.6)" : "#b2ebf2"');
  font-size: 0.9em;
  margin-left: auto;
}

.card-body {
  display: flex;
  align-items: center;
}

.card-img {
  width: 100px;
  height: 70px;
  object-fit: cover;
  border-radius: 6px;
  margin-right: 18px;
  border: 1px solid v-bind('theme === "light" ? "rgba(0, 0, 0, 0.15)" : "rgba(0, 255, 255, 0.15)"');
}

.card-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
}

.card-count, .card-meta {
  color: v-bind('theme === "light" ? "#000" : "#fff"');
  font-size: 1em;
}

.count {
  color: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
  font-weight: bold;
  font-size: 1.2em;
}

.desc {
  font-size: 0.85em;
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.6)" : "#b2ebf2"');
}

.pagination-bar {
  padding: 10px 20px;
  display: flex;
  justify-content: flex-end;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"');
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.1)"');
  border-radius: 12px;
  box-shadow: 0 0 20px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.08)" : "rgba(0, 0, 0, 0.2)"');
}

/* 分页器样式 */
:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-button-color: v-bind('theme === "light" ? "#000" : "#fff"');
  --el-pagination-button-disabled-color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.3)" : "rgba(255, 255, 255, 0.3)"');
  --el-pagination-hover-color: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
}

:deep(.el-pagination .el-pagination__total) {
  color: v-bind('theme === "light" ? "#000" : "#fff"');
}

:deep(.el-pagination .el-pagination__jump) {
  color: v-bind('theme === "light" ? "#000" : "#fff"');
}

:deep(.el-pagination .el-pager li) {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.3)"');
  color: v-bind('theme === "light" ? "#000" : "#fff"');
}

:deep(.el-pagination .el-pager li.active) {
  background: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
  color: v-bind('theme === "light" ? "#fff" : "#000"');
}

:deep(.el-pagination .el-pager li:hover) {
  color: v-bind('theme === "light" ? "#409EFF" : "#00ffff"');
}

.popover-download-row {
  display: flex;
  flex-direction: row;
  gap: 12px;
  justify-content: center;
  align-items: center;
}

.download-btn {
  flex: 1 1 0;
  min-width: 100px;
}
</style>
